import positionTpl from '../../views/position/position.html'
import ItemTpl from '../../views/position/position-item.html'
import { get } from '../model/http'
import BScroll from '@better-scroll/core'
import PullDown from '@better-scroll/pull-down'
import Pullup from '@better-scroll/pull-up'

BScroll.use(PullDown);
BScroll.use(Pullup);

class PositionController {

  constructor() {
    //第几页
    this.pageNo = 1;
    //每页的条数
    this.pageSize = 10;
    //全部的列表数据
    this.datalist = [];
    //是否有更多的数据
    this.isMore = true;

    this.initEvent();
  }

  initEvent() {
    $("#main").on('click', '.item', function () {
      console.log('item click');
      let positionId = $(this).attr('data-id');
      location.href = '/detail.html?' + positionId;
    })
  }

  async getlist() {
    $("#loading").show();
    let url = `/api/positionlist?_page=${this.pageNo}&_limit=${this.pageSize}`;
    let result = await get(url);
    console.log('lagou:', result);
    this.datalist = this.datalist.concat(result);
    if (result.length < this.pageSize) {
      this.isMore = false;
    }
    let html = template.render(ItemTpl, { datalist: this.datalist })
    $(".position-list").html(html)
    $("#loading").hide();
  }


  //单一职责
  async render() {
    $("#swipper-position").html(positionTpl)
    await this.getlist();
    this.ininScroll();
  }


  ininScroll() {
    if (this.scroll) {
      this.scroll.destroy();
    }
    this.scroll = new BScroll('#position-wrapper', {
      scrollY: true,
      //上拉加载更多
      pullUpLoad: true,
      //默认会阻止浏览器的原生 click 事件。当设置为 true，BetterScroll 会派发一个 click 事件
      click: true,
      //下拉刷新
      pullDownRefresh: {
        threshold: 40,
        stop: 0
      }
    })


    //下拉刷新
    this.scroll.on('pullingDown', async () => {
      this.isMore = true;
      $('.more').show();
      this.datalist = [];
      this.pageNo = 1;
      console.log("pullingDown");
      await this.getlist();
      this.scroll.finishPullDown();
      this.scroll.refresh();
      this.ininScroll();
    })

    //监测实时滚动
    this.scroll.on('scroll', function () {
      // console.log(this.y)
      if (this.y > 10) {
        $(".refersh").show()
      } else {
        $(".refersh").hide()
      }
    })

    //上拉加载更多（翻页）
    this.scroll.on('pullingUp', async () => {
      if (!this.isMore) {
        $('.more').hide();
        this.scroll.finishPullUp();
        this.scroll.refresh();
        alert('没有更多的数据了')
        return;
      }
      this.pageNo++;
      console.log('pullingup')
      await this.getlist();
      this.scroll.finishPullUp();
      this.scroll.refresh();
    })
  }
}


export default new PositionController();